//
//  AddressListViewController.m
//  MemberProject
//
//  Created by macbook on 15/4/14.
//  Copyright (c) 2015年 MAC OS X. All rights reserved.
//

#import "AddressListViewController.h"
#import "AddressListTableViewCell.h"
#import "PinYin4Objc.h"
#import "UserInfoManager.h"
#import "Utils.h"
#import "AppDelegate.h"
#import "AddressUser.h"
@interface AddressListViewController ()<UITableViewDelegate,UITableViewDataSource,NSFetchedResultsControllerDelegate,AddressListTableViewCellDelegate,UIAlertViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property(strong,nonatomic)NSArray *data;
@property(strong,nonatomic)NSFetchedResultsController *fetchedResultsController;
//真实的索引
@property(strong,nonatomic)NSArray *keys;

@property(strong,nonatomic)NSArray *indexKeys;

@property(strong,nonatomic)NSArray *sectionIndexKeys;

@property(strong,nonatomic)NSString *tempStr;
@end

@implementation AddressListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"通讯录";
    self.tableView.dataSource=self;
    self.tableView.delegate=self;
    
    ModelUser *modelUser=[UserInfoManager sharedManager].modelMser;
    
    [self.tableView registerNib:[UINib nibWithNibName:@"AddressListTableViewCell" bundle:nil] forCellReuseIdentifier:@"CellIdentifier"];
    
    AppDelegate *app = [UIApplication sharedApplication].delegate;
    NSManagedObjectContext *context = app.managedObjectContext;
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"AddressUser" inManagedObjectContext:context];
    [fetchRequest setEntity:entityDescription];
    [fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"voluteerId = %@",modelUser.voluteerId]];
    //要求3，返回的顺序以升序还是降序排列
    NSSortDescriptor *sortDescriptor1 = [NSSortDescriptor sortDescriptorWithKey:@"index" ascending:YES];
    NSSortDescriptor *sortDescriptor2=[NSSortDescriptor sortDescriptorWithKey:@"pinyin" ascending:YES];
    [fetchRequest setSortDescriptors:@[sortDescriptor1,sortDescriptor2]];

    
    
    _fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:context sectionNameKeyPath:@"index" cacheName:nil];
    _fetchedResultsController.delegate = self;
    //下达查找命令
    NSError *error=nil;
    BOOL isSuccess = [_fetchedResultsController performFetch:&error];
    if (!isSuccess) {
        NSLog(@"error = %@",[error localizedDescription]);
    }

    //建立索引
    NSArray *sections=[_fetchedResultsController sections];
    NSMutableArray *arrM=[NSMutableArray array];
    for(int i=0;i<sections.count;i++){
        AddressUser *user=[_fetchedResultsController objectAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:i]];
        [arrM addObject:user.sectionTitle];
    }
    self.keys=arrM;

    arrM=[NSMutableArray array];
    NSMutableArray *sectionIndexKeys=[NSMutableArray array];
    for(int i=0;i<26;i++){
        NSString *str=[NSString stringWithFormat:@"%c",'A'+i];
        [arrM addObject:str];
        NSPredicate *pre=[NSPredicate predicateWithFormat:@"self = %@",str];
        NSString *tempStr=[[self.keys filteredArrayUsingPredicate:pre] lastObject];
        if(tempStr.length==0){
            [sectionIndexKeys addObject:@(-1)];
        }else{
            [sectionIndexKeys addObject:@([self.keys indexOfObject:tempStr])];
        }
    }
    [arrM addObject:@"#"];
    NSPredicate *pre=[NSPredicate predicateWithFormat:@"self = %@",@"#"];
    NSString *tempStr=[[self.keys filteredArrayUsingPredicate:pre] lastObject];
    if(tempStr.length==0){
        [sectionIndexKeys addObject:@(-1)];
    }else{
        [sectionIndexKeys addObject:@([self.keys indexOfObject:tempStr])];
    }
    self.sectionIndexKeys=sectionIndexKeys;
    self.indexKeys=arrM;
    
    
    
//    NSMutableArray *arrM=[NSMutableArray array];
//    for(int i=0;i<50;i++){
//        [arrM addObject:@{@"name":[NSString stringWithFormat:@"张%d",i],@"tel":[NSString stringWithFormat:@"13232132143%d",i]}];
//    }
//    self.data=arrM;
//    if(self.data.count==0){
//        self.tableView.hidden=YES;
//    }
    NSDictionary *dic = @{@"token":@"sdfsadfsadfasdf",@"module":@"Voluteer",@"method":@"searchVoluteerUser",@"requestId":[NSNull new],@"requestParam":@[modelUser.groupId]};
    [SVProgressHUD show];
    __weak AddressListViewController *this=self;
    [Utils requestDic:dic andRusult:^(id result) {
        if(this){
            [SVProgressHUD dismiss];
            if ([result isKindOfClass:[NSDictionary class]]){
                NSArray *responseData = result[@"responseData"];
                if(![responseData isKindOfClass:[NSNull class]]){
                    [self analyzeWithDic:responseData];
                }
            }
        }
    } andError:^(id result) {
        
    }];
}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [SVProgressHUD dismiss];
}

#pragma mark - analyze
-(void)analyzeWithDic:(NSArray *)arr{
    //删除旧数据
    NSArray *fetchedObjects=[_fetchedResultsController fetchedObjects];
    for(int i=(int)fetchedObjects.count-1;i>=0;i--){
        AddressUser *user=fetchedObjects[i];
        [_fetchedResultsController.managedObjectContext deleteObject:user];

    }
    [_fetchedResultsController.managedObjectContext save:nil];
    
    
    HanyuPinyinOutputFormat *outputFormat=[[HanyuPinyinOutputFormat alloc] init];
    [outputFormat setToneType:ToneTypeWithoutTone];
    [outputFormat setVCharType:VCharTypeWithV];
    [outputFormat setCaseType:CaseTypeLowercase];
//    NSString *outputPinyin=[PinyinHelper toHanyuPinyinStringWithNSString:sourceText withHanyuPinyinOutputFormat:outputFormat withNSString:@" "];
    AppDelegate *app = [UIApplication sharedApplication].delegate;
    NSManagedObjectContext *context = app.managedObjectContext;
    ModelUser *modelUser=[UserInfoManager sharedManager].modelMser;
    for(int i=0;i<arr.count;i++){
        AddressUser *managedObject = [NSEntityDescription insertNewObjectForEntityForName:@"AddressUser" inManagedObjectContext:context];
        managedObject.voluteerId=modelUser.voluteerId;
        NSDictionary *dic=arr[i];
        NSString *loginMobile=dic[@"loginMobile"];
        NSString *userName=dic[@"userName"];
        if(loginMobile.length!=0){
            managedObject.loginMobile=loginMobile;
        }
        if(![userName isKindOfClass:[NSNull class]]&&userName.length!=0&&![userName isEqualToString:@"null"]){
            managedObject.userName=userName;
            
            NSMutableString *pinyin = [[NSMutableString alloc] initWithString:userName];
            if (CFStringTransform((__bridge CFMutableStringRef)pinyin, 0, kCFStringTransformMandarinLatin, NO)) {
            }
            if (CFStringTransform((__bridge CFMutableStringRef)pinyin, 0, kCFStringTransformStripDiacritics, NO)) {
            }
//            NSString *pinyin=[PinyinHelper toHanyuPinyinStringWithNSString:userName withHanyuPinyinOutputFormat:outputFormat withNSString:@" "];
            managedObject.pinyin=pinyin;
            managedObject.index=[[pinyin substringWithRange:NSMakeRange(0, 1)] uppercaseString];
            managedObject.sectionTitle=managedObject.index;
        }else{
            managedObject.index=@"a";
            managedObject.sectionTitle=@"#";
        }
        managedObject.data=[NSJSONSerialization dataWithJSONObject:dic options:0 error:nil];
        //        //3,给NSManagedObject对象赋值------用KVC技术赋值
        //        //但我们生成实体类的时候我们可以用属性的形式访问
        //        managedObject.name = [NSString stringWithFormat:@"%d",i];
        //        managedObject.sex = @"男";
        //        managedObject.no = [NSNumber numberWithInt:i];
    
    }
    NSError *error=nil;
    if (![context save:&error])
    {
        NSLog(@"error= %@",[error localizedDescription]);
    }
    
    //生成索引
    NSArray *sections=[_fetchedResultsController sections];
    NSMutableArray *arrM=[NSMutableArray array];
    for(int i=0;i<sections.count;i++){
        AddressUser *user=[_fetchedResultsController objectAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:i]];
        [arrM addObject:user.sectionTitle];
    }
    self.keys=arrM;
    NSMutableArray *sectionIndexKeys=[NSMutableArray array];
    for(int i=0;i<self.indexKeys.count;i++){
        NSPredicate *pre=[NSPredicate predicateWithFormat:@"self = %@",self.indexKeys[i]];
        NSString *tempStr=[[self.keys filteredArrayUsingPredicate:pre] lastObject];
        if(tempStr.length==0){
            [sectionIndexKeys addObject:@(-1)];
        }else{
            [sectionIndexKeys addObject:@([self.keys indexOfObject:tempStr])];
        }
    }
    [self.tableView reloadData];
}

#pragma mark - Table view data source
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    return self.indexKeys;
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index{
    return [self.sectionIndexKeys[index] integerValue];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _fetchedResultsController.sections.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    id<NSFetchedResultsSectionInfo>  info = _fetchedResultsController.sections[section];
    return [info numberOfObjects];//该区中有多少个对象
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier=@"CellIdentifier";
    AddressListTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    AddressUser *user = [_fetchedResultsController objectAtIndexPath:indexPath];
    cell.nameLabel.text=user.userName;
    cell.telLabel.text=user.loginMobile;
    cell.delegate=self;
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view=[[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 23)];
    view.backgroundColor=[UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1];
    UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(10, 0, SCREEN_WIDTH-10, view.height)];
    label.backgroundColor=[UIColor clearColor];
    AddressUser *user=[_fetchedResultsController objectAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:section]];
    label.textAlignment=NSTextAlignmentLeft;
    label.text=user.sectionTitle;
    [view addSubview:label];
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 23;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 44;
}

#pragma mark - NSFetchedResultsController
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller{
//    [self.tableView beginUpdates];
}

-(void)controller:(NSFetchedResultsController *)controller didChangeSection:(id<NSFetchedResultsSectionInfo>)sectionInfo atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type
{
//    switch (type) {
//        case NSFetchedResultsChangeDelete:
//            [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationNone];
//            break;
//        case NSFetchedResultsChangeInsert:
//            [self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationNone];
//            break;
//        default:
//            break;
//    }
}
-(void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath
{
//    UITableView *tableView = self.tableView;
//    switch(type) {
//            
//        case NSFetchedResultsChangeInsert:
//            [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]
//                             withRowAnimation:UITableViewRowAnimationFade];
//            break;
//            
//        case NSFetchedResultsChangeDelete:
//            [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
//                             withRowAnimation:UITableViewRowAnimationFade];
//            break;
//            
//        case NSFetchedResultsChangeUpdate:
//            [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
//            break;
//            
//        case NSFetchedResultsChangeMove:
//            [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
//                             withRowAnimation:UITableViewRowAnimationFade];
//            [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]
//                             withRowAnimation:UITableViewRowAnimationFade];
//            break;
//    }
}
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
//    [self.tableView endUpdates];
}

#pragma mark - cell delegate
-(void)chickCallButtonWithAddressListTableViewCell:(AddressListTableViewCell *)cell{
    NSIndexPath *indexPath=[self.tableView indexPathForCell:cell];
    AddressUser *user=[_fetchedResultsController objectAtIndexPath:indexPath];
    NSString *loginMobile=user.loginMobile;
    self.tempStr=loginMobile;
    NSString *str=[NSString stringWithFormat:@"呼叫 %@",loginMobile];
    UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"提示" message:str delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alertView show];
}

-(void)chickSMSButtonWithAddressListTableViewCell:(AddressListTableViewCell *)cell{
    NSIndexPath *indexPath=[self.tableView indexPathForCell:cell];
    AddressUser *user=[_fetchedResultsController objectAtIndexPath:indexPath];
    NSString *loginMobile=user.loginMobile;
    NSString *urlStr=[NSString stringWithFormat:@"sms://%@",loginMobile];
    if([[UIApplication sharedApplication]canOpenURL:[NSURL URLWithString:urlStr]]){
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr]];
    }else{
        UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"提示" message:@"该设备不支持短信功能" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alertView show];
    }
}

#pragma mark - alertView
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(buttonIndex==1){
        NSString *urlStr=[NSString stringWithFormat:@"tel://%@",self.tempStr];
        if([[UIApplication sharedApplication]canOpenURL:[NSURL URLWithString:urlStr]]){
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr]];
        }else{
            UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"提示" message:@"该设备不支持呼叫功能" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alertView show];
        }
    }
}

@end
